//
//  AddMediaViewController.m
//  Nurse
//
//  Created by RainSets on 14-9-14.
//  Copyright (c) 2014年 Honeywell. All rights reserved.
//

#import "AddMediaViewController.h"
#import <MediaPlayer/MediaPlayer.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import "PatientService.h"
#import "CreatVideoViewController.h"
//#import "DBCameraContainerViewController.h"
//#import "DBCameraMovieContainerViewController.h"
#import "AViewController.h"
#import "MediaImproveController.h"
#import "RecordViewController.h"

@interface AddMediaViewController ()<UINavigationControllerDelegate, UIImagePickerControllerDelegate>
@property (weak, nonatomic) IBOutlet UIButton *btnAddImage;
- (IBAction)addImageAction:(id)sender;
@property (weak, nonatomic) IBOutlet UIButton *btnAddVoice;
- (IBAction)addVoiceAction:(id)sender;
@property (weak, nonatomic) IBOutlet UIButton *btnAddVideo;
- (IBAction)addVideoAction:(id)sender;

@property (nonatomic, strong) UINavigationController *nav;
@property (strong, nonatomic) UIImagePickerController *imagePicker;
@end

@implementation AddMediaViewController
@synthesize nav = _nav;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (UIImagePickerController *)imagePicker
{
    if (_imagePicker == nil) {
        _imagePicker = [[UIImagePickerController alloc] init];
        _imagePicker.delegate = self;
    }
    
    return _imagePicker;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self setTitle:@"添加媒体"];
    NSDictionary* patient = [[PatientService sharedInstance]currentPatient];
    self.pInfoView.txtPatientName.text = [patient valueForKey:@"姓名"];
    self.pInfoView.txtPatientID.text = [NSString stringWithFormat:@"住院号:%@",[patient valueForKey:@"住院号"]];
    self.pInfoView.txtBedNo.text = [NSString stringWithFormat:@"床位号:%@",[patient valueForKey:@"床位号"]];
    NSString*xb= [patient valueForKey:@"性别"];
    if ([xb isEqualToString:@"女"]) {
        self.pInfoView.imgxb.image=[UIImage imageNamed:@"gender-female2.png"];
    }
    else{
        self.pInfoView.imgxb.image=[UIImage imageNamed:@"gender-male2.png"];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)addImageAction:(id)sender {
//    DBCameraContainerViewController *cameraContainer = [[DBCameraContainerViewController alloc] initWithDelegate:self];
//    [cameraContainer setFullScreenMode];
//    
//    _nav = [[UINavigationController alloc] initWithRootViewController:cameraContainer];
//    [_nav setNavigationBarHidden:YES];
//    [self presentViewController:_nav animated:YES completion:nil];
#if TARGET_IPHONE_SIMULATOR
    NSLog(@"模拟器不支持拍照");
#elif TARGET_OS_IPHONE
    self.imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
    self.imagePicker.mediaTypes = @[(NSString *)kUTTypeImage];
    [self presentViewController:self.imagePicker animated:YES completion:NULL];
#endif
}
- (IBAction)addVoiceAction:(id)sender {
    RecordViewController *recordVC = [[RecordViewController alloc] initWithNibName:@"RecordViewController" bundle:nil];
    _nav = [[UINavigationController alloc] initWithRootViewController:recordVC];
    [_nav setNavigationBarHidden:YES];
    [self presentViewController:_nav animated:YES completion:nil];
}
- (IBAction)addVideoAction:(id)sender {
//    DBCameraMovieContainerViewController *cameraContainer = [[DBCameraMovieContainerViewController alloc] initWithDelegate:self];
//    [cameraContainer setFullScreenMode];
//    
//    _nav = [[UINavigationController alloc] initWithRootViewController:cameraContainer];
//    [_nav setNavigationBarHidden:YES];
//    [self presentViewController:_nav animated:YES completion:nil];
#if TARGET_IPHONE_SIMULATOR
    NSLog(@"模拟器不支持录像");
#elif TARGET_OS_IPHONE
    self.imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
    self.imagePicker.mediaTypes = @[(NSString *)kUTTypeMovie];
    [self presentViewController:self.imagePicker animated:YES completion:NULL];
#endif
}

#pragma mark - helper
- (NSURL *)convert2Mp4:(NSURL *)movUrl {
    NSURL *mp4Url = nil;
    AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:movUrl options:nil];
    NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:avAsset];
    
    if ([compatiblePresets containsObject:AVAssetExportPresetHighestQuality]) {
        AVAssetExportSession *exportSession = [[AVAssetExportSession alloc]initWithAsset:avAsset
                                                                              presetName:AVAssetExportPresetHighestQuality];
        mp4Url = [movUrl copy];
        mp4Url = [mp4Url URLByDeletingPathExtension];
        mp4Url = [mp4Url URLByAppendingPathExtension:@"mp4"];
        exportSession.outputURL = mp4Url;
        exportSession.shouldOptimizeForNetworkUse = YES;
        exportSession.outputFileType = AVFileTypeMPEG4;
        dispatch_semaphore_t wait = dispatch_semaphore_create(0l);
        [exportSession exportAsynchronouslyWithCompletionHandler:^{
            switch ([exportSession status]) {
                case AVAssetExportSessionStatusFailed: {
                    NSLog(@"failed, error:%@.", exportSession.error);
                } break;
                case AVAssetExportSessionStatusCancelled: {
                    NSLog(@"cancelled.");
                } break;
                case AVAssetExportSessionStatusCompleted: {
                    NSLog(@"completed.");
                } break;
                default: {
                    NSLog(@"others.");
                } break;
            }
            dispatch_semaphore_signal(wait);
        }];
        int timeout = dispatch_semaphore_wait(wait, DISPATCH_TIME_FOREVER);
        if (timeout) {
            NSLog(@"timeout.");
        }
        if (wait) {
            //dispatch_release(wait);
            wait = nil;
        }
    }
    
    return mp4Url;
}

#pragma mark - UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSString *mediaType = info[UIImagePickerControllerMediaType];
    if ([mediaType isEqualToString:(NSString *)kUTTypeMovie]) {
        NSURL *videoURL = info[UIImagePickerControllerMediaURL];
        [picker dismissViewControllerAnimated:YES completion:^{
            [self.navigationController setNavigationBarHidden:YES animated:YES];
            
        // we will convert it to mp4 format
//        NSURL *mp4 = [self convert2Mp4:videoURL];
//        NSFileManager *fileman = [NSFileManager defaultManager];
//        if ([fileman fileExistsAtPath:videoURL.path]) {
//            NSError *error = nil;
//            [fileman removeItemAtURL:videoURL error:&error];
//            if (error) {
//                NSLog(@"failed to remove file, error:%@.", error);
//            }
//        }
//        NSLog(@"[mp4 relativePath]==%@",[mp4 relativePath]);
            
            MediaImproveController *mediaImpVC = [[MediaImproveController alloc] initWithNibName:@"MediaImproveController" bundle:nil];
            [mediaImpVC setBtnDetailVideo:videoURL];
            [self.navigationController pushViewController:mediaImpVC animated:YES];
        }];
    }else{
        UIImage *orgImage = info[UIImagePickerControllerOriginalImage];
        [picker dismissViewControllerAnimated:YES completion:nil];
        
        AViewController *detailV = [[AViewController alloc] initWithNibName:@"AViewController" bundle:nil];
        [detailV setDetailImage:orgImage];
        [self.navigationController pushViewController:detailV animated:YES];
//        MediaImproveController *mediaImpVC = [[MediaImproveController alloc] initWithNibName:@"MediaImproveController" bundle:nil];
//        [self.navigationController pushViewController:mediaImpVC animated:YES];
//        [mediaImpVC setBtnDetailImg:orgImage];
    }
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self.imagePicker dismissViewControllerAnimated:YES completion:^{
        [self.navigationController setNavigationBarHidden:NO animated:YES];
    }];
    
}

/*
#pragma mark - DBCameraViewControllerDelegate

- (void) dismissCamera:(id)cameraViewController{
    [self.presentedViewController dismissViewControllerAnimated:YES completion:nil];
    [cameraViewController restoreFullScreenMode];
}

- (void) camera:(id)cameraViewController didFinishWithImage:(UIImage *)image withMetadata:(NSDictionary *)metadata
{
    
    AViewController *detailV = [[AViewController alloc] initWithNibName:@"AViewController" bundle:nil];
    [detailV setDetailImage:image];
    [_nav pushViewController:detailV animated:YES];
//    [cameraViewController restoreFullScreenMode];
//    [self.presentedViewController dismissViewControllerAnimated:YES completion:nil];
}

-(void)camera:(id)cameraMovieViewController didFinishWithMovieUrl:(NSURL *)fileUrl withError:(NSError *)error{
    if (!error) {
        DLog(@"fileUrl==%@",fileUrl);
        MediaImproveController *mediaImpVC = [[MediaImproveController alloc] initWithNibName:@"MediaImproveController" bundle:nil];
        [mediaImpVC setBtnDetailVideo:fileUrl];
        [_nav pushViewController:mediaImpVC animated:YES];
    }
}
*/
@end
